package org.liaohailong.library.widget.statusbar;

import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;


import org.liaohailong.library.util.OSUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 状态栏工具类
 *
 * @author wujianning
 */

public class StatusBarUtil {

    /**
     * 外部调用
     * 设置状态栏模式
     *
     * @param activity     Activity对象
     * @param isTextDark   文字&图标是否为黑色(false为默认的白色)
     * @param isLocalColor 本地颜色还是获取的rgb颜色值
     * @param colorId      状态栏颜色
     */

    public static void setStatusBarMode(Activity activity, boolean isTextDark, boolean isLocalColor, int colorId) {
        if (!isActivityIsAlive(activity)) return;
        if (!isTextDark) {//文字&图标颜色不变 只修改状态栏颜色
            setStatusBarColor(activity, isLocalColor, colorId);
        } else {//修改状态栏颜色和文字图标颜色
            setStatusBarColor(activity, isLocalColor, colorId);
            //4.4以上才可以改文字图标颜色
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                if (OSUtil.isMIUI()) {//小米系统
                    setMIUIStatusBarTextMode(activity, isTextDark);
                } else if (OSUtil.isFlyme()) {//魅族系统
                    setFlymeStatusBarTextMode(activity, isTextDark);
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//6.0以上 其他手机系统 调用系统方法
                    try {
                        Window window = activity.getWindow();
                        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }  //4.4以上6.0以下的其他系统，暂时没有修改状态栏的文字图标颜色的方法，有可以加上
            }
        }
    }

    /**
     * 修改状态栏颜色，支持4.4以上版本
     *
     * @param activity     Activity对象
     * @param isLocalColor 本地颜色还是获取的rgb颜色值
     * @param colorId      状态栏颜色
     */

    private static void setStatusBarColor(Activity activity, boolean isLocalColor, int colorId) {
        if (!isActivityIsAlive(activity)) return;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//Android6.0(API 21)以上系统
            Window window = activity.getWindow();
            if (isLocalColor) {
                window.setStatusBarColor(colorId);
            } else {
                window.setStatusBarColor(activity.getResources().getColor(colorId));
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//Android5.0(API 19)以上系统
            //使用SystemBarTint库使4.4版本状态栏变色，需要先将状态栏设置为透明
            setTranslucentStatus(activity);
            //设置状态栏颜色
            SystemBarTintManager tintManager = new SystemBarTintManager(activity);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(colorId);
        }
    }

    /**
     * 设置状态栏为透明
     *
     * @param activity Activity对象
     */

    @TargetApi(19)
    private static void setTranslucentStatus(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//Android6.0(API 21)以上系统
            try {
                Window window = activity.getWindow();
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//Android5.0(API 19)以上系统
            try {
                Window window = activity.getWindow();
                window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 设置MIUI系统状态栏的文字图标颜色（MIUIV6以上）
     *
     * @param activity Activity对象
     * @param isDark   状态栏文字及图标是否为深色
     */

    private static void setMIUIStatusBarTextMode(Activity activity, boolean isDark) {
        if (!isActivityIsAlive(activity)) return;
        Window window = activity.getWindow();
        if (window != null) {
            Class clazz = window.getClass();
            try {
                int darkModeFlag;
                Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
                Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
                darkModeFlag = field.getInt(layoutParams);
                Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
                if (isDark) {
                    extraFlagField.invoke(window, darkModeFlag, darkModeFlag);//状态栏透明且黑色字体
                } else {
                    extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
                }

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    //开发版 7.7.13 及以后版本采用了系统API，旧方法无效但不会报错，所以两个方式都要加上
                    if (isDark) {
                        activity.getWindow().getDecorView().setSystemUiVisibility(View
                                .SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View
                                .SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                    } else {
                        activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
                    }
                }
            } catch (Exception ignored) {

            }
        }
    }

    /**
     * 设置MeiZu系统状态栏的文字图标颜色
     *
     * @param activity Activity对象
     * @param isDark   状态栏文字及图标是否为深色
     */
    public static void setFlymeStatusBarTextMode(Activity activity, boolean isDark) {
        if (!isActivityIsAlive(activity)) return;
        Window window = activity.getWindow();
        if (window != null) {
            try {
                WindowManager.LayoutParams lp = window.getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meiZuFlags = WindowManager.LayoutParams.class.getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meiZuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meiZuFlags.getInt(lp);
                if (isDark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meiZuFlags.setInt(lp, value);
                window.setAttributes(lp);
            } catch (Exception ignored) {

            }
        }
    }

    /**
     * 判断当前Activity是否处于正常状态 显示Dialog时 判断Dialog依附的当前Activity是否处于正常状态
     */
    public static boolean isActivityIsAlive(Activity activity) {
        return null != activity && !activity.isFinishing() && !activity.isDestroyed();
    }
}
